import {
  ReactChild,
  ReactFragment,
  ReactPortal,
  useState,
  useLayoutEffect,
  useEffect,
  useMemo,
  useRef,
} from 'react';
import { Grid, Toast } from 'antd-mobile';
import { message } from 'antd';
import { InbizIcon, getPreView, getEditor, h5Utils, getProgressRoute } from '@inbiz/utils';
import BizTitle from '@inbiz/basic/BizTitle';
import BizBody from '@inbiz/basic/BizBody';
import BizHeader from '@inbiz/basic/BizHeader';
import { TextWidget, getMessage } from '@inbiz/react';
import EasyView from './EasyView';
import Home from './Home';
import ProcessApply from './ProcessApply';
import Approval from './ProcessApproval';
import ProcessLog from '@inbiz/basic/WapProcessLog';
import ProcessSetAssign from './ProcessSetAssign';
import { saveProcessGroup } from '../web/service';
import {
  mobiltableedynamicdata as mobiledynamicdataDefault,
  h5_easydynamicdata as h5_easydynamicdataDefault,
} from '../../designer/option';
import './index.less';

const hideSelectbyList = (data: any) => {
  return data.filter((item: { hide: any }) => !item.hide)
}
const ProcessCenter = (props: any) => {
  const {
    columns,
    gap,
    title,
    titleIcon,
    mobiledynamicdata = mobiledynamicdataDefault,
    h5_easydynamicdata = h5_easydynamicdataDefault,
    mobiltableedynamicdata = mobiledynamicdataDefault,
    h5_tableDefaultPage,
    className,
    radius,
    inbiz,
    tabVisible = true,
    rangeConfig,
    processGroup,
    h5_viewType,
    associatedPage,
    customClickItem,
  } = props;
  const applyRef = useRef({ getCategory: Function, searchApply: Function });
  const homeRef = useRef<any>();
  const easyRef = useRef({ getData: Function });
  const refreshRef = useRef<number>(0);
  const isEditor = getEditor();
  const [routeParams, setRouteParams] = useState(getProgressRoute());
  const { userInfoByToken, userInfo } = inbiz.appInfo;
  const _userInfo = userInfoByToken || { ID: userInfo?.guid };
  const [processMainData, $processMainData] = useState(mobiledynamicdata);
  const [easyData, $easyData] = useState(h5_easydynamicdata);
  const [homeData, $homeData] = useState(mobiltableedynamicdata);

  useEffect(() => {
    $processMainData(hideSelectbyList(mobiledynamicdata))
  }, [mobiledynamicdata])

  useEffect(() => {
    $easyData(hideSelectbyList(h5_easydynamicdata))
  }, [h5_easydynamicdata])

  useEffect(() => {
    $homeData(hideSelectbyList(mobiltableedynamicdata))
  }, [mobiltableedynamicdata])


  useEffect(() => {
    setRouteParams(getProgressRoute());
  }, [window.location.hash]);

  const ProcessMain = (props: any) => (
    <div className={'ProcessCenter'}>
      {/* 标题组件 */}
      <BizHeader {...props}>
        <BizTitle titleOption={title} iconOption={titleIcon} />
      </BizHeader>
      <BizBody {...props}>
        <Grid columns={columns} gap={gap}>
          {processMainData.map(
            (
              item: {
                id: string;
                icon: { type: any; color: any; size: any };
                titleColor: any;
                title: boolean | ReactChild | ReactFragment | ReactPortal | null | undefined;
                page: string;
              },
              index: string,
            ) => (
              <Grid.Item key={item.id + '' + index} style={{ borderRadius: radius ? radius : '' }}>
                <div
                  onClick={() => {
                    if (isEditor) {
                      return Toast.show({
                        content: getMessage('processCenter.previewOperation'),
                      });
                    } else {
                      if (associatedPage) {
                        let path = associatedPage.split(',')[0];
                        window.location.href =
                          getPreView(path) + `/${item.page}?type=mobile&tabKey=${item?.id}`;
                      } else {
                        // 请联系管理员配置关联页面
                        message.warning(getMessage('FolderPanel.lang.configureAssociationPage'));
                      }
                    }
                  }}
                >
                  <p />
                  <InbizIcon
                    className={'icon'}
                    type={item.icon?.type || 'icon-ic-shezhi'}
                    style={{
                      color: item.icon?.color || '#108ee9',
                      fontSize: item.icon?.size || '32px',
                    }}
                  />
                  <p style={{ color: item.titleColor }}>
                    <TextWidget>{item.title}</TextWidget>
                  </p>
                </div>
              </Grid.Item>
            ),
          )}
        </Grid>
      </BizBody>
    </div>
  );

  const getComponent = () => {
    let component = null;
    switch (routeParams) {
      case 'apply':
        component = (
          <ProcessApply
            userInfo={_userInfo}
            rangeConfig={rangeConfig}
            processGroup={processGroup}
            ref={applyRef}
          />
        );
        break;
      case 'approval':
        component = <Approval inbiz={inbiz} userInfo={_userInfo} />;
        break;
      case 'log':
        component = <ProcessLog inbiz={inbiz} userInfo={_userInfo} />;
        break;
      case 'setassign':
        component = <ProcessSetAssign userInfo={_userInfo} />;
        break;
      case 'todo':
      case 'applying':
      case 'draft':
      case 'toMe':
      case 'myApply':
      case 'done':
      case 'classification':
      case 'assigned':
      case 'receive':
      case 'willassign':
        component = (
          <Home
            tabVisible={tabVisible}
            userInfo={_userInfo}
            tabsArray={homeData}
            rangeConfig={rangeConfig}
            processGroup={processGroup}
            customClickItem={customClickItem}
            ref={homeRef}
          />
        );
        break;
      default:
        component = (
          <ProcessApply
            userInfo={_userInfo}
            rangeConfig={rangeConfig}
            processGroup={processGroup}
            ref={applyRef}
          />
        );
        break;
    }
    return component;
  };

  const saveProcessGroupData = () => {
    const needSaveProcessGroup = localStorage.getItem('needSaveProcessGroup');
    if (needSaveProcessGroup == '1' && rangeConfig == 'custom') {
      const groupIds =
        processGroup.selectedRows
          .map((item: { value: any; id: any }) => item.value || item.id)
          .join() || '-1';
      saveProcessGroup({
        key: processGroup?.groupGuid ?? '',
        groupIds,
      }).then((res) => {
        if (res.code == '200') {
          localStorage.setItem('needSaveProcessGroup', '0');
          if (h5_viewType == 'processTable') {
            if (routeParams == 'apply') {
              applyRef?.current?.getCategory();
              applyRef?.current?.searchApply();
            } else {
              const equalIndex = window.location.href.indexOf('tabKey');
              homeRef?.current?.changeTab(
                window.location.href.slice(equalIndex + 7, equalIndex + 8),
              );
            }
          } else if (h5_viewType == 'easy') {
            easyRef?.current?.getData();
          }
        } else {
          Toast.show({
            icon: 'fail',
            content: res.messaged,
          });
        }
      });
    }
  };

  useEffect(() => {
    h5Utils.inbizPageEvent.off('pageSave');
    h5Utils.inbizPageEvent.on('pageSave', () => {
      saveProcessGroupData();
    });

    return () => {
      h5Utils.inbizPageEvent.off('pageSave');
    };
  }, [saveProcessGroupData, h5_viewType]);

  useEffect(() => {
    h5Utils.inbizPageEvent.on('menuClickJump', (item:any ) => {
      refreshRef.current =new Date().getTime();
    })
    return () => {
      h5Utils.inbizPageEvent.off('menuClickJump');
    };
  }, [])

  const keyToType = useMemo(() => {
    switch (h5_tableDefaultPage) {
      case '1':
        return 'apply';
      case '2':
        return 'todo';
      case '3':
        return 'applying';
      case '4':
        return 'draft';
      case '5':
        return 'toMe';
      case '6':
        return 'myApply';
      case '7':
        return 'done';
      case '8':
        return 'classification';
      case '9':
        return 'assigned';
      case '10':
        return 'willassign';
      case '11':
        return 'receive';
      default:
        return 'apply';
    }
  }, [h5_tableDefaultPage]);

  useEffect(() => {
    if (h5_viewType == 'processTable') {
      if (isEditor) {
        const href = window.location.href;
        const equalIndex = href.indexOf('tabKey');
        if (equalIndex > -1) {
          let _hash = window.location.hash;
          let _hashArray = _hash?.split('/');
          let _type = _hashArray?.[_hashArray?.length - 1]?.split('?')?.[0];
          let _typeIndex = href?.indexOf(_type);
          let newHref = href.slice(0, equalIndex + 7) + h5_tableDefaultPage;
          let _newHref = newHref;
          let __newHref = newHref;
          newHref =
            _newHref.slice(0, _typeIndex) +
            ([
              'apply',
              'todo',
              'applying',
              'draft',
              'toMe',
              'myApply',
              'done',
              'classification',
              'assigned',
              'willassign',
              'receive',
            ].includes(_type)
              ? keyToType
              : _type) +
            __newHref.slice(href.indexOf('?', _typeIndex));
          window.history.replaceState({}, '', `${newHref}`);
        } else {
          if (href.indexOf('#log') < 0 && href.indexOf('ids') < 0) {
            window.history.replaceState(
              {},
              '',
              `${href}/${keyToType}?type=mobile&tabKey=${h5_tableDefaultPage}`,
            );
          }
        }
        let _hash = window.location.hash;
        let _hashArray = _hash?.split('/');
        let _type = _hashArray?.[_hashArray?.length - 1]?.split('?')?.[0];
        setRouteParams(_type);
      } else {
        const href = window.location.href;
        const equalIndex = href.indexOf('tabKey');
        if (equalIndex == -1) {
          if (href.indexOf('#log') < 0 && href.indexOf('ids') < 0) {
            window.history.replaceState(
              {},
              '',
              `${href}/${keyToType}?type=mobile&tabKey=${h5_tableDefaultPage}`,
            );
          }
          // setRouteParams(keyToType);
        }
      }
    }
  }, [h5_viewType, h5_tableDefaultPage, isEditor, refreshRef.current]);

  useLayoutEffect(() => {
    setTimeout(() => {
      homeRef?.current?.initialConditions();
      homeRef?.current?.getInitData(h5_tableDefaultPage);
    }, 50);
  }, [h5_tableDefaultPage]);

  if (h5_viewType == 'easy') {
    return (
      <EasyView {...props} userInfo={_userInfo} h5_easydynamicdata={easyData} ref={easyRef} />
    );
  } else if (h5_viewType == 'pure') {
    return <ProcessMain {...props} inbiz={inbiz} userInfo={_userInfo} />;
  } else if (h5_viewType == 'processTable') {
    return (
      <div className={className} style={{ height: '100%', marginRight: '1px' }}>
        {getComponent()}
      </div>
    );
  } else {
    return null;
  }
};

export default ProcessCenter;
